#include "aht20.h"
#include "i2c.h"

void AHT20_Init(void) {
    // 1. 发送初始化命令
    uint8_t init_cmd[3] = {0xBE, 0x08, 0x00};
    HAL_I2C_Master_Transmit(&hi2c1, AHT20_I2C_ADDR, init_cmd, 3, 100);
    HAL_Delay(10);

    // 2. 校准传感器（可选）
    uint8_t calib_cmd[3] = {0xE1, 0x08, 0x00};
    HAL_I2C_Master_Transmit(&hi2c1, AHT20_I2C_ADDR, calib_cmd, 3, 100);
    HAL_Delay(300);
}

void AHT20_ReadData(AHT20_Data *data) {
    // 1. 触发测量
    uint8_t trigger_cmd[3] = {0xAC, 0x33, 0x00};
    HAL_I2C_Master_Transmit(&hi2c1, AHT20_I2C_ADDR, trigger_cmd, 3, 100);
    HAL_Delay(80); // 等待测量完成

    // 2. 读取数据
    uint8_t raw_data[6];
    HAL_I2C_Master_Receive(&hi2c1, AHT20_I2C_ADDR, raw_data, 6, 100);

    // 3. 数据转换
    uint32_t raw_humidity = ((raw_data[1] << 16) | (raw_data[2] << 8) | raw_data[3]) >> 4;
    uint32_t raw_temp = ((raw_data[3] & 0x0F) << 16) | (raw_data[4] << 8) | raw_data[5];

    data->humidity = (raw_humidity * 100.0) / 1048576.0;
    data->temperature = (raw_temp * 200.0 / 1048576.0) - 50.0;
}
